package fun.flyee.android.pengshan.acts;

import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import com.hcvsa.CloseAVChannel;
import com.hcvsa.MyHCVSA;
import com.hcvsa.OnCMSLoginStatus;
import com.hcvsa.OpenAVChannel;
import com.hcvsa.UserAcceptCall;
import com.hcvsa.UserHandUpCall;
import com.hcvsa.UserOffline;
import com.hcvsa.UserRejectCall;
import com.squareup.otto.Subscribe;
import com.until.BusProvider;
import com.view.MyVideoRel2;

import butterknife.BindView;
import butterknife.OnClick;
import fun.flyee.android.pengshan.utils.Systems;
import fun.flyee.pengshan.social.R;
import hcvs.audio.AudioCapture;
import hcvs.camera.ICameraSurface;
import hcvs.hcvsa.MeetingEvent;

public class CallActivity extends BaseNotifyActivity {

    private int sessionid;        //用户回话ID，每个在线用户拥有唯一的sessionid
    private int calltype;
    @BindView(R.id.myVideoRel)
    public MyVideoRel2 myVideoRel;
    @BindView(R.id.root_view)
    public View rootView;
    @BindView(R.id.switch_camera_btn)
    public View cameraBtn;
    @BindView(R.id.hangup_btn)
    public View hangupBtn;

    private OpenAVChannel currentChannel;

    protected int layoutId() {
        return R.layout.act_call;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD //解锁
                | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON //保持屏幕不息屏
                | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);//点亮屏幕
        Systems.hideSystemNavBar(this);
        if (Build.VERSION.SDK_INT > 27) {
            setShowWhenLocked(true);
        } else {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
        }
        WindowManager.LayoutParams params = getWindow().getAttributes();
        params.systemUiVisibility = View.SYSTEM_UI_FLAG_LOW_PROFILE;
        getWindow().setAttributes(params);
        BusProvider.getInstance().register(this);
        sessionid = getIntent().getIntExtra("sessionid", 0);
        calltype = getIntent().getIntExtra("calltype", 0);
        if (calltype == MeetingEvent.HCVS_CALL_TYPE_AUDIO) {
            cameraBtn.setVisibility(View.GONE);
            myVideoRel.setVisibility(View.INVISIBLE);
        }
        myVideoRel.setOnRemoteChannel((happen -> {
            currentChannel = happen;
            delayUpdateUIHandler.sendEmptyMessageDelayed(0, 1000);
        }));
        initSpeak();
//        bindRootView(rootView);
    }

    Handler delayUpdateUIHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            myVideoRel.updateUI();
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        hideNotify();
        if (currentChannel != null && Build.VERSION.SDK_INT >= 24) {
            myVideoRel.OpenAVChannel(currentChannel);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        showNotify();
        if (currentChannel != null) {
            CloseAVChannel closeAVChannel = new CloseAVChannel(
                    currentChannel.getType(), currentChannel.getId(),
                    currentChannel.getChannel(), currentChannel.getType2());
            myVideoRel.CloseAVChannel(closeAVChannel);
        }
    }

    @Override
    public void onDestroy() {
        BusProvider.getInstance().unregister(this);
        if (myVideoRel != null) {
            try {
                myVideoRel.release();
            } catch (Throwable throwable) {
                throwable.printStackTrace();
            }
        }
        //关闭我的视频通道
        MyHCVSA.getInstance().CloseMyVideoChannel();
        super.onDestroy();
    }

    private void initSpeak() {
        if (calltype == MeetingEvent.HCVS_CALL_TYPE_AV) {
            myVideoRel.setOpenMyVideo(true);
        } else {
            myVideoRel.setOpenMyVideo(false);
        }
        //接受呼叫
        MyHCVSA.getInstance().getUserSessionMoudle().OnMyAcceptCall(sessionid, calltype);
        myVideoRel.postDelayed(() -> {
            //打开我的视频
            MyHCVSA.getInstance().OpenMyVideoChannel();
        }, 500);

    }

    @OnClick(R.id.switch_camera_btn)
    public void onCameraSwitch() {
        ICameraSurface cs = myVideoRel.getCameraSurface(0);
        if(cs!=null){
            cs.cameraFacingChanged();
        }
    }

    @Subscribe
    public void UserHandUpCall(UserHandUpCall data) {
        Toast.makeText(this, "用户挂断了与你的通话！", Toast.LENGTH_LONG).show();
        finish();
    }

    @Subscribe
    public void UserOffline(UserOffline data) {
        if (sessionid == data.getUser().getSessionid()) {
            Toast.makeText(this, "用户下线了！", Toast.LENGTH_LONG).show();
            finish();
        }
    }

    @Subscribe
    public void onCMSLoginStatus(OnCMSLoginStatus data) {
        if (data.getLoginStatus() == 0) {
            Toast.makeText(this, "与服务器断开连接！", Toast.LENGTH_LONG).show();
            try {
                MyHCVSA.getInstance().getUserSessionMoudle().OnMyCallHandUp(sessionid, calltype);
            }catch (Exception e){

            }
            finish();
        }
    }

    @Subscribe
    public void UserRejectCall(UserRejectCall data) {
        Toast.makeText(this, "用户拒绝了你的呼叫", Toast.LENGTH_LONG).show();
        finish();
    }

    @Subscribe
    public void UserAcceptCall(UserAcceptCall data) {
        Toast.makeText(this, "用户接受了你的呼叫", Toast.LENGTH_LONG).show();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            this.hangup();
            return true;
        } else
            return super.onKeyDown(keyCode, event);
    }

    @OnClick(R.id.hangup_btn)
    public void hangup() {
        MyHCVSA.getInstance().getUserSessionMoudle().OnMyCallHandUp(sessionid, calltype);
        finish();
    }

//    @OnClick(R.id.fixed_btn)
//    public void onFixedClick() {
//        super.toFixed();
//        cameraBtn.setVisibility(View.VISIBLE);
//        hangupBtn.setVisibility(View.VISIBLE);
//    }

}
